import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;

public class MusicPlayer extends Thread{
    //下面是音乐播放模块
    ModularMain modularMain;
    DmjMain dmjMain;
    public MusicPlayer(ModularMain modularMain1,DmjMain dmjMain1){
        modularMain = modularMain1;
        dmjMain = dmjMain1;
    }
    private AudioFormat getOutFormat(AudioFormat inFormat) {
        final int ch = inFormat.getChannels();
        final float rate = inFormat.getSampleRate();
        return new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, rate, 16, ch, ch * 2, rate, false);
    }
    private void stream(AudioInputStream in, SourceDataLine line)
            throws IOException {
        final byte[] buffer = new byte[65536];
        for (int n = 0; n != -1; n = in.read(buffer, 0, buffer.length)) {
            line.write(buffer, 0, n);

            if (modularMain.next){
                return;
            }
        }
    }
    public void play(String filePath) {
        final File file = new File(filePath);

        try {
            final AudioInputStream in = AudioSystem.getAudioInputStream(file);

            final AudioFormat outFormat = getOutFormat(in.getFormat());

            final DataLine.Info info = new DataLine.Info(SourceDataLine.class, outFormat);

            final SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);

            if (line != null) {
                line.open(outFormat);
                line.start();
                stream(AudioSystem.getAudioInputStream(outFormat, in), line);
                line.drain();
                line.stop();
            }
            modularMain.next = false;

        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    @Override
    public void run() {
        while (true){
            if (modularMain.waitList.size()>0){
                File music = new File("./music/"+modularMain.waitList.get(0)+".mp3");
                modularMain.playing = modularMain.waitList.get(0);
                modularMain.waitList.remove(0);
                try{
                    play(music.getPath());
                } catch (Exception e){
                    dmjMain.newLogCallback("[点歌姬]:",music.getName()+" 播放失败");
                }
                music.delete();
                modularMain.playing ="";
            }else {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
